// 创建slice需要一个字符串名称来标识切片
// 一个初始state以及一个或者多个定义了该如何更新state的reducer函数
// slice创建后，我们可以导出slice中生成的Redux action creators和reducer函数

import { createSlice } from "@reduxjs/toolkit";

export const counterSlice = createSlice({
    name: "counter",
    initialState: {
        value: 0,
    },
    reducers: {
        increment: (state) => {
            state.value +=1;
        },
        decrement: (state) => {
            state.value -= 1;
        },
        incrementByAmount: (state,action) => {
            state.value += action.payload;
        }
    }
})


// export const incrementAsync = (amount) => (dispatch) => {
//     setTimeout(() => {
//       dispatch(incrementByAmount(amount))
//     }, 1000)
// }

export const incrementAsync = (amount) => {
    return (dispatch) => {
        setTimeout(() => {
            dispatch(incrementByAmount(amount))
        }, 1000)
    }
}

// 每个case reducer函数生成对应的Action creators
export const { increment,decrement,incrementByAmount } = counterSlice.actions;

// 等价于
//export const increment = counterSlice.actions.increment;
//export const decrement = counterSlice.actions.decrement;
//export const incrementByAmount = counterSlice.actions.incrementByAmount;

// counterSlice.actions.increment()：生成 { type: 'counter/increment' }

// const newState = counterSlice.reducer(
//     { value: 10 },
//     counterSlice.actions.increment()
// );
// console.log('newState',newState);

export default counterSlice.reducer;